package com.API.dal.providers;

import com.API.dal.entities.Incomes;
import com.API.dal.entities.IncomesCustomersProjects;
import com.API.dal.entities.Objects;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public class IncomesProviderImp implements IncomeProvider {


    @Autowired
    SessionFactory sessionFactory;

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public Incomes getIncomeById(int id) {
        Incomes income;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Incomes inc where inc.id = " + id);
        income = (Incomes) query.uniqueResult();
        return income;
    }

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public List<Incomes> getIncomes() {
        List<Incomes> incomes;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Incomes inc ");
        incomes =  query.list();
        return incomes;
    }

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public Objects getCustomer(int income_id) {
        Objects customer;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("select ob from Objects ob, IncomesCustomersProjects icp " +
                "where ob.id = icp.objectsByProjectId.id and icp.incomes.id = " + income_id);
        customer = (Objects) query.uniqueResult();
        return customer;
    }

    @Override
    @Transactional(readOnly=true,propagation= Propagation.SUPPORTS)
    public Objects getProject(int income_id) {
        Objects project;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("select ob from Objects ob, IncomesCustomersProjects icp " +
                "where ob.id = icp.objectsByProjectId.id and icp.incomes.id = " + income_id);
        project = (Objects) query.uniqueResult();
        return project;
    }
}
